package com.zpself.module.多线程.Lock;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author By ZengPeng
 * @Description
 * @date in  2021/3/5 17:12
 * @Modified By
 */
public class 分析CyclicBarrier {
    @Test
    public void  test() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CountDownLatch cd = new CountDownLatch(1);

        int threadNumber = 5;
        //都到的时候做点事
        CyclicBarrier cb = new CyclicBarrier(threadNumber, new Runnable() {
            @Override
            public void run() {
                System.out.println("线程："+Thread.currentThread().getName()+"最后一个贵宾入场！并通知了主持人！");
                cd.countDown();
            }
        });

        System.out.println("主持人准备中....");

        //所有客宾线程
        for (int i = 0; i <threadNumber; i++) {
            executorService.execute(() -> {
                try {
                    System.out.println("线程："+Thread.currentThread().getName()+"进入party");
                    cb.await();
                    System.out.println("线程："+Thread.currentThread().getName()+"收到party开始，就坐！");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }


        cd.await();
        //主持人等待人齐： 发表演讲
        System.out.println("主持人发言：欢迎大家来参加我的葬礼.....");
    }
}
